package com.weilive.core.protocol.protobuf;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.weilive.core.utils.ClassUtils;


public class ProtobufCodec {
	
	private static final Logger log = LoggerFactory.getLogger(ProtobufCodec.class);
	
	private static final HashMap<String, ProtobufRequestHandler> handlers = new HashMap<String, ProtobufRequestHandler>();
	
	public static void loadBySearch(String pkgName) {
		for (Class<?> c : ClassUtils.getClassList(pkgName, true, ProtobufRequestHandler.class)) {
			try {
				ProtobufRequestHandler handler = (ProtobufRequestHandler)c.newInstance();
				handlers.put(handler.getRequestType().getClass().getSimpleName(), handler);
				log.info("===> load protobuf handler:"+handler.getRequestType().getClass().getSimpleName());
			} catch (Exception e) {
			}
		}
	}
	
	public static void loadBySpring(ApplicationContext context) {
		for (ProtobufRequestHandler handler : context.getBeansOfType(ProtobufRequestHandler.class).values()) {
			handlers.put(handler.getRequestType().getClass().getSimpleName(), handler);
			log.info("===> load protobuf handler:"+handler.getRequestType().getClass().getSimpleName());
		}
	}
	
	public static boolean isHandlerForTypeImplement(String type) {
		return handlers.containsKey(type);
	}
	
	public static ProtobufRequestHandler getHandlerByType(String type) {
		return handlers.get(type);
	}
}
